/**
 * @fileoverview wrapper for combined queue and target functionality
 *
 * @author Sebastian Brzuzek sebastian@brzuzek.pl
 */

goog.provide('uxperf.Collector');

goog.require('uxperf.Queue');
goog.require('uxperf.target.TargetFactory');
goog.require('uxperf.target.TargetBase');
goog.require('goog.events.EventTarget');

/**
 * collector constructor
 *
 * @param {Function=} opt_callback function to call after collector initialization
 * @constructor
 * @extends {goog.events.EventTarget}
 */
uxperf.Collector = function(opt_callback) {
	/**
	 * flag if collector is ready to accept events
	 * @type {boolean}
	 */
	this.ready_ = false;
	
	var queue = this.queue_ = uxperf.Queue.getInstance();
	if (opt_callback) {
		goog.events.listenOnce(queue, uxperf.Queue.EVENT_TYPES.READY, opt_callback);
	}
	goog.events.listenOnce(queue, uxperf.Queue.EVENT_TYPES.READY, this);
	this.target_ = uxperf.target.TargetFactory.getInstance(function (e) {
		queue.init();
	});
	//initialize collecting flow
	goog.events.listen(queue, uxperf.Queue.EVENT_TYPES.SEND, this.target_);
	goog.events.listen(this.target_, uxperf.Queue.EVENT_TYPES.SENT, queue);
};
goog.inherits(uxperf.Collector, goog.events.EventTarget);
goog.addSingletonGetter(uxperf.Collector);

/**
 * queue instance (singleton)
 * @type {uxperf.Queue}
 */
uxperf.Collector.prototype.queue_ = null;

/**
 * target instance
 * @type {uxperf.target.TargetBase}
 */
uxperf.Collector.prototype.target_ = null;

/**
 * if collector is ready to accept events
 * @return {boolean}
 */
uxperf.Collector.prototype.isReady = function() { return this.ready_; };

/**
 * event handler implementation
 * @param {goog.events.Event|Event|Object} e event to handle
 */
uxperf.Collector.prototype.handleEvent = function(e) {
	switch (e.type) {
		case uxperf.Queue.EVENT_TYPES.READY:
			this.ready_ = true;
			break;
		//default:
			//
	}
};

/**
 * initialization of collector
 */
uxperf.Collector.prototype.init = function() {
	if (this.ready_) return; //check if already initialized
	
	//initialize queue
	var queue = this.queue_ = uxperf.Queue.getInstance();
	queue.init();
	
	this.ready_ = queue.isReady();
};